package ua.khpi.si.kit49.diploma.db.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ua.khpi.si.kit49.diploma.db.dto.User;

/**
 * Implementation of user DAO
 * 
 * @author netstalk3r
 * 
 */

@Repository("userDAO")
public class UserDAOImpl implements UserDAO {

	private static final String QUERY_GET_ALL_USERS = "FROM User";
	private static final String QUERY_GET_USER_BY_ID = "FROM User WHERE id = :id";
	private static final String QUERY_GET_USER_BY_EMAIL = "FROM User WHERE email = :email";
	private static final String QUERY_GET_USER_BY_USERNAME = "FROM User WHERE username = :username";
	private static final String QUERY_DELETE_USERS = "DELETE FROM User WHERE id IN (:ids)";
	private static final String QUERY_BAN_USERS = "UPDATE User SET enabled = :enabled WHERE id IN (:ids)";

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	@Override
	public User getUserById(Integer id) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_USER_BY_ID).setParameter("id", id)
				.uniqueResult();
	}

	@Override
	public User getUserByEmail(String email) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_USER_BY_EMAIL)
				.setParameter("email", email).uniqueResult();
	}

	@Override
	public User getUserByUsername(String username) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_USER_BY_USERNAME)
				.setParameter("username", username).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAllUsers() {
		return sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_ALL_USERS).list();
	}

	@Override
	public void saveOrUpdateUser(User user) {
		sessionFactory.getCurrentSession().saveOrUpdate(user);
	}

	@Override
	public void removeUsers(List<Integer> ids) {
		sessionFactory.getCurrentSession().createQuery(QUERY_DELETE_USERS)
				.setParameterList("ids", ids).executeUpdate();

	}

	@Override
	public void banUsers(List<Integer> ids, Boolean enabled) {
		sessionFactory.getCurrentSession().createQuery(QUERY_BAN_USERS)
				.setParameter("enabled", enabled).setParameterList("ids", ids)
				.executeUpdate();

	}

}
